﻿using Bangle.SerialPort.Messages;
using System;
using System.Threading.Tasks;

namespace Bangle.SerialPort
{
    public abstract class AbstractAbpSerialPortService : ISerialPortService
    {
        protected virtual Task OnException(Exception ex)
        {
            return Task.CompletedTask;
        }

        protected virtual Task OnDataReceived(byte[] data)
        {
            return Task.CompletedTask;
        }

        public virtual Task OnOpenAsync(System.IO.Ports.SerialPort serialPort)
        {
            return Task.CompletedTask;
        }

        public Task DoAsync(System.IO.Ports.SerialPort serialPort)
        {
            byte[] buffer = new byte[serialPort.BytesToRead];
            serialPort.Read(buffer, 0, buffer.Length);

            return OnDataReceived(buffer);
        }
    }

    public abstract class AbstractAbpSerialPortService<TMessage> : AbstractAbpSerialPortService
       where TMessage : IMessage, new()
    {
        protected override Task OnDataReceived(byte[] data)
        {
            var reader = new BufferReader(data);
            var msg = new TMessage();
            msg.Deserialize(reader);
            return OnDataReceived(msg);
        }

        protected abstract Task OnDataReceived(TMessage msg);
    }
}
